// Package endpoint
// Author liuzhiyong
// Date 2023/11/28
// Description
package rpc_client

import (
	"gitee.com/liu_zy_developer/go-kit-demo/transport"
	"io"
	"time"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	sdconsul "github.com/go-kit/kit/sd/consul"
	"github.com/go-kit/kit/sd/lb"
	"github.com/hashicorp/consul/api"
	apiconsul "github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
)

// GetTrimServiceFromConsul 基于consul的服务发现
func GetTrimServiceFromConsul(consulAddr string, srvName string, tags []string, logger log.Logger) (endpoint.Endpoint, error) {
	consulConfig := apiconsul.DefaultConfig()
	consulConfig.Address = consulAddr

	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		return nil, err
	}

	sdClient := sdconsul.NewClient(consulClient)
	var passingOnly = true
	instancer := sdconsul.NewInstancer(sdClient, logger, srvName, tags, passingOnly)
	endpointer := sd.NewEndpointer(instancer, factory, logger)
	balancer := lb.NewRoundRobin(endpointer)
	retryMax := 3
	retryTimeout := 500 * time.Millisecond
	retry := lb.Retry(retryMax, retryTimeout, balancer)
	return retry, nil
}

func factory(instance string) (endpoint.Endpoint, io.Closer, error) {
	conn, err := grpc.Dial(instance, grpc.WithInsecure())
	if err != nil {
		return nil, nil, err
	}

	e := transport.NewTrimGrpcClient(conn)
	return e, conn, err
}
